package com.anjie.powerproject.controller;

import com.anjie.powerproject.common.Result;
import com.anjie.powerproject.entity.StationInfo;
import com.anjie.powerproject.entity.WeatherData;
import com.anjie.powerproject.repository.StationInfoRepository;
import com.anjie.powerproject.repository.WeatherRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
@RequestMapping("weather")
public class WeatherForecastController {
    @Autowired
    WeatherRepository weatherRepository;
    @Autowired
    StationInfoRepository stationInfoRepository;
    /**
     * 数据预处理
     */
    @RequestMapping(value = "/getWeatherDataDaily")
    @ResponseBody
    public Result getWeatherDataDaily(@RequestParam(defaultValue = "none",value = "date") String date) {
        if(date.equals("none")) {
            Date curDate=new Date();
            date = new SimpleDateFormat("yyyy-MM-dd").format(curDate);
        }

        StationInfo stationInfo=stationInfoRepository.findStationInfoLimitFirst();
        WeatherData weatherData=weatherRepository.getWeatherForecastDataByDate(stationInfo.getCityCode(),date);

        return Result.ok(weatherData);
    }


    @RequestMapping(value ={ "/getWeatherDataHourly/{date}","/getWeatherDataHourly"})
    @ResponseBody
    public Result getWeatherDataHourly(@PathVariable(value = "date",required = false) String date) {
        Date curDate=new Date();
        String ymd = new SimpleDateFormat("yyyyMMdd").format(curDate);

        if (date==null||date.equals("")){//没传日期，默认获取当天日期
            date=ymd;
        }

        WeatherData weatherData=null;

        String cityCode=stationInfoRepository.findStationInfoLimitFirst().getCityCode();
        if (ymd.equals(date)){  //是当天，取当前小时的温度返回
            //dayTMax dayTMin都是数据库中的Temperature字段 dayHumMax dayHumMin都是humidity字段的值
            date = new SimpleDateFormat("yyyy-MM-dd HH").format(curDate);
            weatherData=weatherRepository.getWeatherForecastDataByHour(cityCode, date);
        }else {//不是是当天，取传入那天的最高温度返回
            date=date.substring(0,4)+'-'+date.substring(4,6)+'-'+date.substring(6,8);  //拼接成yyyy-mm-dd格式
            weatherData=weatherRepository.getWeatherForecastDataByDate(cityCode,date);
        }

        if(weatherData!=null)
            return Result.ok(weatherData);
        else return Result.error("天气数据为空! 请检查输入日期是否正确或确认数据库中有该天的数据");
    }
}
